//
//  UIView+Test.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2023/8/3.
//  Copyright © 2023 moon. All rights reserved.
//

#import "UIView+Test.h"

@implementation UIView (Test)
- (void)test_playShakingAnimating{
    // 晃动次数
    int numberOfShakes = 4;
    // 晃动幅度（相对于总宽度）
    float vigourOfShake = 0.04f;
    // 晃动延续时常（秒）
    float durationOfShake = 0.5f;
     
    CAKeyframeAnimation *shakeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
     
        // 方法一：绘制路径
//        CGRect frame = self.view.frame;
//        // 创建路径
//        CGMutablePathRef shakePath = CGPathCreateMutable();
//        // 起始点
//        CGPathMoveToPoint(shakePath, NULL, CGRectGetMidX(frame), CGRectGetMidY(frame));
//        for (int index = 0; index < numberOfShakes; index++)
//        {
//            // 添加晃动路径 幅度由大变小
//            CGPathAddLineToPoint(shakePath, NULL, CGRectGetMidX(frame) - frame.size.width * vigourOfShake*(1-(float)index/numberOfShakes),CGRectGetMidY(frame));
//            CGPathAddLineToPoint(shakePath, NULL,  CGRectGetMidX(frame) + frame.size.width * vigourOfShake*(1-(float)index/numberOfShakes),CGRectGetMidY(frame));
//        }
//        // 闭合
//        CGPathCloseSubpath(shakePath);
//        shakeAnimation.path = shakePath;
//        shakeAnimation.duration = durationOfShake;
//        // 释放
//        CFRelease(shakePath);
     
    // 方法二：关键帧（点）
    CGPoint layerPosition = self.layer.position;
     
    // 起始点
    NSValue *value1=[NSValue valueWithCGPoint:self.layer.position];
    // 关键点数组
    NSMutableArray *values = [[NSMutableArray alloc] initWithObjects:value1, nil];
    for (int i = 0; i<numberOfShakes; i++) {
        // 左右晃动的点
        NSValue *valueLeft = [NSValue valueWithCGPoint:CGPointMake(layerPosition.x-self.frame.size.width*vigourOfShake*(1-(float)i/numberOfShakes), layerPosition.y)];
        NSValue *valueRight = [NSValue valueWithCGPoint:CGPointMake(layerPosition.x+self.frame.size.width*vigourOfShake*(1-(float)i/numberOfShakes), layerPosition.y)];
         
        [values addObject:valueLeft];
        [values addObject:valueRight];
    }
    // 最后回归到起始点
    [values addObject:value1];
     
    shakeAnimation.values = values;
    shakeAnimation.duration = durationOfShake;
     
    [self.layer addAnimation:shakeAnimation forKey:kCATransition];
}
@end
